package com.amsp.oa.oademo.service.impl;

import com.amsp.oa.oademo.entity.ProductInventory;
import com.amsp.oa.oademo.entity.ProductInventoryItem;
import com.amsp.oa.oademo.mapper.ProductInventoryMapper;
import com.amsp.oa.oademo.mapper.ProductInventoryItemMapper;
import com.amsp.oa.oademo.service.ProductInventoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ProductInventoryServiceImpl extends ServiceImpl<ProductInventoryMapper, ProductInventory>
        implements ProductInventoryService {

    @Autowired
    private ProductInventoryItemMapper itemMapper;

    @Override
    public Page<ProductInventory> getPage(Integer current, Integer size) {
        Page<ProductInventory> page = new Page<>(current, size);
        return this.page(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveWithItems(ProductInventory productInventory) {
        LocalDateTime now = LocalDateTime.now();
        if (productInventory.getId() != null) {
            // 更新
            productInventory.setUpdateTime(now);
            // 删除原有明细
            LambdaQueryWrapper<ProductInventoryItem> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ProductInventoryItem::getInventoryId, productInventory.getId());
            itemMapper.delete(wrapper);
        } else {
            // 新增
            productInventory.setCreateTime(now);
            productInventory.setUpdateTime(now);
        }

        boolean success = this.saveOrUpdate(productInventory);
        if (success && productInventory.getItemList() != null) {
            List<ProductInventoryItem> itemList = productInventory.getItemList();
            for (ProductInventoryItem item : itemList) {
                item.setInventoryId(productInventory.getId());
                item.setCreateTime(now);
                item.setUpdateTime(now);
                itemMapper.insert(item);
            }
        }
        return success;
    }

    @Override
    public ProductInventory getDetailById(Long id) {
        ProductInventory productInventory = this.getById(id);
        if (productInventory != null) {
            LambdaQueryWrapper<ProductInventoryItem> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ProductInventoryItem::getInventoryId, id);
            List<ProductInventoryItem> itemList = itemMapper.selectList(wrapper);
            productInventory.setItemList(itemList);
        }
        return productInventory;
    }
}